<template>
  <NavBar title="邀请好友记录" color="#fff" colorText="#333" brg="#f8f8f8">
  <view class="invite-friends-container">
    <!-- 我的好友横幅 -->
    <view class="friends-banner">
      <view class="banner-left">
        <view class="friends-icon">
          <image class="friends-icon-img" src="/static/ren.png" mode=""></image>
        </view>
        <text class="banner-title">我的好友</text>
      </view>
      <view class="friends-count"><text class="friends-count-text">{{ totalFriends }}</text> 人</view>
    </view>
    
    <!-- 好友记录列表 -->
    <view class="friends-list">
      <view 
        v-for="(friend, index) in friendsList" 
        :key="index"
        class="friend-item"
      >
        <view class="friend-avatar">
          <view class="robot-avatar">
              <image class="robot-avatar-image" :src="friend.avatar" mode="aspectFill"></image>
          </view>
        </view>
        <view class="friend-info">
          <text class="friend-name">{{ friend.name }}</text>
        </view>
        <text class="friend-date">{{ friend.date }}</text>
        <view class="friend-divider" v-if="index < friendsList.length - 1"></view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && friendsList.length === 0">
      <image class="empty-icon" src="/static/empty.png" mode="widthFix"></image>
      <text class="empty-text">暂无邀请好友记录</text>
    </view>
  </view>
  </NavBar>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { USER_API } from '../../config/api.js'
import { getToken, isLoggedIn } from '../../utils/user.js'

// 响应式数据
const totalFriends = ref(0)
const friendsList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''

  try {
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateTimeStr
  }
}

// 处理头像URL
const processAvatar = (avatar) => {
  let avatarUrl = '/static/profile/avatar.jpg' // 默认头像

  // 特殊处理默认头像
  if (avatar && avatar === 'https://devoss.igmdns.com/avatar/avatar.jpg') {
    avatarUrl = '/static/profile/avatar.jpg'
  } else if (avatar && avatar.startsWith('http')) {
    // 对于网络图片，添加时间戳防止缓存
    const timestamp = Date.now()
    avatarUrl = avatar.includes('?')
      ? `${avatar}&t=${timestamp}`
      : `${avatar}?t=${timestamp}`
  }

  return avatarUrl
}

// 方法
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取数据
onMounted(() => {
  loadFriendsList()
})

const loadFriendsList = async () => {
  // 检查登录状态
  const loginStatus = isLoggedIn()
  if (!loginStatus) {
    console.log('用户未登录，不请求好友记录接口')
    friendsList.value = []
    totalFriends.value = 0
    return
  }

  if (loading.value) return

  try {
    loading.value = true

    const token = getToken()
    if (!token) {
      console.error('未找到用户token')
      return
    }

    // 构建请求参数
    const params = {
      page: currentPage.value,
      page_size: pageSize.value
    }

    // 构建查询字符串
    const queryString = Object.keys(params)
      .map(key => `${key}=${encodeURIComponent(params[key])}`)
      .join('&')

    console.log('请求好友列表API:', `${USER_API.USER_FRIENDS}?${queryString}`)

    const response = await uni.request({
      url: `${USER_API.USER_FRIENDS}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })

    console.log('好友列表API响应:', response)

    if (response.statusCode === 200 && response.data.code === 200) {
      const responseData = response.data.data

      if (responseData && responseData.list) {
        // 处理好友列表数据
        const newFriends = responseData.list.map(friend => ({
          name: friend.nickname || friend.username || friend.name || '未知用户',
          date: formatDateTime(friend.created_at || friend.register_time || friend.invite_time),
          avatar: processAvatar(friend.avatar || friend.avatar_url)
        }))

        console.log('处理后的好友数据:', newFriends)

        if (currentPage.value === 1) {
          friendsList.value = newFriends
        } else {
          friendsList.value = [...friendsList.value, ...newFriends]
        }

        // 更新总数 - 从 friend_count 字段读取
        totalFriends.value = responseData.friend_count || responseData.total || friendsList.value.length

        // 检查是否还有更多数据 - 从 has_more 字段读取
        hasMore.value = responseData.has_more !== undefined ? responseData.has_more : (newFriends.length === pageSize.value)
      } else {
        console.log('没有好友数据')
        if (currentPage.value === 1) {
          friendsList.value = []
          totalFriends.value = 0
        }
        hasMore.value = false
      }
    } else {
      console.error('获取好友列表失败:', response.data)
      const errorMessage = response.data?.data?.error_message || response.data?.error_message || response.data?.message || '获取好友列表失败'

      uni.showToast({
        title: errorMessage,
        icon: 'none',
        duration: 3000
      })
    }
  } catch (error) {
    console.error('获取好友列表失败:', error)
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none',
      duration: 3000
    })
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.invite-friends-container {
  min-height: 100vh;
background: linear-gradient( 180deg, #C2DDFF 0%, #FFFFFF 100%);
border-radius: 0rpx 0rpx 0rpx 0rpx;
padding-top: 160rpx;
  position: relative;
}

/* 状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx 10rpx;
  background: transparent;
}

.status-time {
  font-size: 34rpx;
  font-weight: 600;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.status-icons {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.status-icon {
  font-size: 24rpx;
  color: #000;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 40rpx;
  background: #E3F2FD;
}

.back-button {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 30rpx;
  background: rgba(255, 255, 255, 0.2);
}

.back-icon {
  font-size: 32rpx;
  color: #666;
  font-weight: bold;
}

.nav-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #000;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.nav-placeholder {
  width: 60rpx;
  height: 60rpx;
  background: white;
  border-radius: 8rpx;
}

/* 我的好友横幅 */
.friends-banner {
  background: #2196F3;
  margin: 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(  #84B9FF 0%, #64A2F4 100%);
}

.banner-left {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.friends-icon {
  width: 60rpx;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-text {
  font-size: 32rpx;
  color: white;
}

.banner-title {
  font-size: 32rpx;
  font-weight: 600;
  color: white;
}

.friends-count {
  font-size: 34rpx;
  font-weight: 600;
  color: white;
}

/* 好友记录列表 */
.friends-list {
  background: white;
  margin: 30rpx 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  position: relative;
}

.friend-avatar {
  margin-right: 24rpx;
}

.robot-avatar {
  position: relative;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}
.robot-avatar-image{
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%,-50%);
	width: 70rpx;
	height: 70rpx;
	border-radius: 50%;
}
.friends-count-text{
	font-size: 38rpx;
}
.robot-head {
  width: 60rpx;
  height: 60rpx;
  background: linear-gradient(135deg, #9C27B0 0%, #7B1FA2 100%);
  border-radius: 30rpx;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}
.friends-icon-img{
	width: 60rpx;
	height: 40rpx;
}
.robot-screen {
  width: 40rpx;
  height: 30rpx;
  background: white;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.robot-face {
  font-size: 16rpx;
}

.robot-body {
  width: 50rpx;
  height: 20rpx;
  background: #2196F3;
  border-radius: 10rpx;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: -2rpx;
}

.robot-x {
  font-size: 14rpx;
  color: white;
  font-weight: bold;
}

.robot-antenna {
  position: absolute;
  top: -8rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 4rpx;
  height: 12rpx;
  background: #9C27B0;
  border-radius: 2rpx;
}

.friend-info {
  flex: 1;
  margin-right: 20rpx;
}

.friend-name {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
}

.friend-date {
  font-size: 24rpx;
  color: #999;
}

.friend-divider {
  position: absolute;
  bottom: 0;
  left: 30rpx;
  right: 30rpx;
  height: 1rpx;
  background: repeating-linear-gradient(
    to right,
    #E0E0E0 0rpx,
    #E0E0E0 8rpx,
    transparent 8rpx,
    transparent 16rpx
  );
}

/* 加载状态 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 80rpx 40rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  width: 146rpx;
  height: 200rpx;
  margin-top: 250rpx;
}

.empty-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #666;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 24rpx;
  color: #999;
  line-height: 1.4;
}

/* 响应式适配 */
@media screen and (max-width: 750rpx) {
  .friend-item {
    padding: 24rpx;
  }
  
  .friend-name {
    font-size: 26rpx;
  }
  
  .friends-banner {
    padding: 24rpx;
  }
}

/* 安全区域适配 */
@supports (padding: max(0px)) {
  .invite-friends-container {
    padding-bottom: max(0px, env(safe-area-inset-bottom));
  }
}
</style>

